/*
 * ========================================================
 * Copyright(c) 2014 杭州龙骞科技-版权所有
 * ========================================================
 * 本软件由杭州龙骞科技所有, 未经书面许可, 任何单位和个人不得以
 * 任何形式复制代码的部分或全部, 并以任何形式传播。
 * 公司网址
 * http://www.hzdracom.com/
 * ========================================================
 */
package com.shwread.android.ui.page;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.shwread.android.qysw.activity.ForgetPwdActivity;
import com.shwread.android.qysw.activity.NewLoginActivity;
import com.shwread.android.qysw.activity.RegisterInformationActivity;
import com.shwread.android.qysw10000152.R;
import com.shwread.android.ui.dialog.NetworkDialog;
import com.shwread.http.ActionHelp;
import com.shwread.http.base.TextHttpResponseHandler;
import com.shwread.http.util.JSONUtil;
import com.shwread.httpsdk.constant.ResultCode;
import com.shwread.httpsdk.http.callback.ActionListener;
import com.tgx.tina.android.ipc.framework.IUIPage;

import org.apache.http.Header;
import org.json.JSONException;

import base.tina.core.task.infc.ITaskResult;
import logic.util.NetworkUtil;
import logic.util.Util;


/**
 * @Project： Lqyd_Android
 * @Title：CheckCodeGetPage
 * @Description：忘记密码第一步获取验证码
 * @Author：wayne
 * @Date：2014年8月14日下午4:20:54
 */
public class CheckCodeGetPage
        extends
        AbstractUIPage<ForgetPwdActivity>
        implements
        OnClickListener
{
	public final static String NAME          = "food_xml";
	protected String           RETRIEVE_TIME = "retrieve_key";
	private static final int   VALIDATE_SEC  = 60;
	private TextView           tvTitle;
	private Button             btnBack;
	
	private TextView           btnVerify;
	private EditText           account;
	private String             mAccount;
	private TextView           btnNextAble;
	private TextView           btnNextEnable;
	private EditText           mes;
	
	private int                mark;
	
	/**
	 * <p>
	 * Title:
	 * </p>
	 * <p>
	 * Description:
	 * </p>
	 * 
	 * @param t
	 */
	public CheckCodeGetPage(ForgetPwdActivity t) {
		super(t);
	}
	
	@Override
	public <E extends Activity> View createView(E arg0, int arg1) {
		if (null != curMyView) return curMyView;
		curMyView = bActivity.getLayoutInflater().inflate(R.layout.login_forget_pwd, null);
		Intent intent = bActivity.getIntent();
		mark = intent.getIntExtra("mark", 0);
		initView();
		btnNextAble.setVisibility(View.GONE);
		btnNextEnable.setVisibility(View.VISIBLE);
		setListener();
		
		return curMyView;
	}
	
	void initView() {
		tvTitle = (TextView) curMyView.findViewById(R.id.common_header_name);
		if (mark == 1)
		{
			tvTitle.setText("注册帐号");
		}
		else
		{
			tvTitle.setText("忘记密码");
		}
		btnBack = (Button) curMyView.findViewById(R.id.common_header_back);
		btnBack.setVisibility(View.VISIBLE);
		account = (EditText) curMyView.findViewById(R.id.login_forget_pwd_account);
		btnVerify = (TextView) curMyView.findViewById(R.id.user_info_setting_recharge_info_test_code_btn);
		btnNextAble = (TextView) curMyView.findViewById(R.id.login_forget_pwd_next_btn_able);
		btnNextEnable = (TextView) curMyView.findViewById(R.id.login_forget_pwd_next_btn_enable);
		mes = (EditText) curMyView.findViewById(R.id.login_forget_validate_input);
	}
	
	void setListener() {
		btnBack.setOnClickListener(this);
		btnVerify.setOnClickListener(this);
		btnNextAble.setOnClickListener(this);
		mes.addTextChangedListener(new TextChanged());
	}
	
	private class TextChanged
	        implements
	        TextWatcher
	{
		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			final String code = s.toString().trim();
			if (!TextUtils.isEmpty(code))
			{
				boolean b = (code.length() == 6);
				btnNextAble.setVisibility(b ? View.VISIBLE : View.GONE);
				btnNextEnable.setVisibility(b ? View.GONE : View.VISIBLE);
			}
		}
		
		@Override
		public void beforeTextChanged(CharSequence s, int start, int count, int after) {
		}
		
		@Override
		public void afterTextChanged(Editable s) {
		}
	}
	
	@Override
	public boolean handleBack() {
		Intent intent = new Intent(bActivity, NewLoginActivity.class);
		bActivity.startActivity(intent);
		return super.handleBack();
	}
	
	@Override
	public int enter(IUIPage<?> arg0) {
		return 0;
	}
	
	@Override
	public int leave(IUIPage<?> arg0) {
		return 0;
	}
	
	@Override
	public void notifyView(int arg0, Bundle arg1) {
		
	}
	
	@Override
	public void setStatus(int arg0) {
		
	}
	
	@Override
	public View updateView(int arg0, ITaskResult arg1) {
		return null;
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.common_header_back:
				Intent intent = new Intent(bActivity, NewLoginActivity.class);
				bActivity.startActivity(intent);
				bActivity.finish();
				break;
			case R.id.user_info_setting_recharge_info_test_code_btn:
				// bActivity.changePage(new CheckCodePage(bActivity),
				// KEEP_LAST_STATUS);
				clickGetcode();
				break;
			case R.id.login_forget_pwd_next_btn_able:
				next();
				//				mAccount = account.getText().toString().trim();
//								Intent nextIntent = new Intent(bActivity, RegisterInformationActivity.class);
//								nextIntent.putExtra("account", mAccount);
//								bActivity.startActivity(nextIntent);
				break;
			default:
				break;
		}
	}
	
	private void next() {
		if (NetworkUtil.isConnected(bActivity))
		{
			nextNext();
		}
		else
		{
			new NetworkDialog(bActivity).show();
		}
	}
	
	String mesString;
	
	// TODO
	private void nextNext() {
		mAccount = account.getText().toString().trim();
		mesString = mes.getText().toString().trim();
		if (Util.isEmpty(mAccount))
		{
			Util.ToastShow(context, "请输入手机号获取短信验证码");
		}
		else if (!Util.isMobile(mAccount))
		{
			Util.ToastShow(context, "请输入正确的手机号");
		}
		else
		{
			if (mark == 1)
			{
				ActionHelp.checkVerificationCode(context, mAccount, mesString, 1, new RegisterNextHandler());
			}
			else
			{
				ActionHelp.resetPasswordSecondStep(context, mAccount, mesString, new NextHandler());
			}
		}
	}
	
	private void clickGetcode() {
		mAccount = account.getText().toString().trim();
		if (Util.isEmpty(mAccount))
		{
			Util.ToastShow(context, "请输入手机号");
		}
		else if (!Util.isMobile(mAccount))
		{
			//			Util.ToastShow(context, "请输入正确的手机号");
			Util.ToastShow(context, "手机号码不正确");
		}
		else if (mark == 1)
		{
			btnVerify.setEnabled(false);
			ActionHelp.getVerificationCode(context, mAccount, 1, new getVerificationHandler());
		}
		else
		{
			btnVerify.setEnabled(false);
			//			new ResetPasswordFirstStepAction(bActivity, mAccount, new MyAction()).start();
			ActionHelp.resetPasswordFirstStep(context, mAccount, new MyHandler());
			
		}
	}
	
	// private void clickGetcode() {
	// if (NetworkUtil.isConnected(bActivity))
	// {
	// checkLoginNext();
	// }
	// else
	// {
	// new NetworkDialog(bActivity).show();
	// }
	// }
	//
	// private void checkLoginNext() {
	// String accountString = account.getText().toString().trim();
	// if (Util.isEmpty(accountString))
	// {
	// Util.showToast(bActivity, "请输入手机号码");
	// }
	// else if (!Util.isMobile(accountString))
	// {
	// Util.showToast(bActivity, "请输入正确的手机号码");
	// }
	// else
	// {
	// Const.clear();
	// new ResetPasswordFirstStepAction(bActivity, accountString, new
	// MyAction()).start();
	// }
	//
	// }
	private static synchronized void doEnable(long l, final TextView tv, final long validate_second) {
		tv.setEnabled(false);
		tv.setTag(tagTime, l);
		if (l < validate_second * 1000)
		{
			Runnable action = new Runnable()
			{
				
				@Override
				public void run() {
					long l = (Long) tv.getTag(tagTime);
					tv.setText(Html.fromHtml("<FONT COLOR='#c6c6c6'>" + "重新获取(" + (validate_second - l / 1000) + "s)</FONT>"));
					l += 1000;
					doEnable(l, tv, validate_second);
				}
			};
			tv.setTag(tagDoing, action);
			tv.postDelayed(action, 1000);
			
		}
		else
		{
			tv.setText(tv.getTag(tagText).toString());
			tv.setEnabled(true);
			tv.setTag(tagDoing, null);
		}
	}
	
	public static long toLong(Object tag) {
		return toLong(tag, 0);
	}
	
	public static long toLong(Object tag, long def) {
		long i = 0;
		try
		{
			i = Long.parseLong(tag.toString());
		}
		catch (Exception e)
		{
			i = def;
		}
		return i;
	}
	
	public static long getLongValue(Context context, String key, long defValue) {
		return context.getSharedPreferences(NAME, Context.MODE_PRIVATE).getLong(key, defValue);
	}
	
	public static void putLongValue(Context context, String key, long value) {
		context.getSharedPreferences(NAME, Context.MODE_PRIVATE).edit().putLong(key, value).commit();
	}
	
	public synchronized static boolean validateRegTime(TextView et, String key) {
		return validateRegTime(et, key, VALIDATE_SEC);
	}
	
	static int tagDoing = 0;
	static int tagTime  = 0;
	static int tagText  = 0;
	
	public synchronized static boolean validateRegTime(TextView tv, String key, long validate_second) {
		if (tagDoing == 0)
		{
			try
			{
				Class<?> id = Class.forName(tv.getContext().getPackageName() + ".R$id");
				Object obj = id.newInstance();
				
				tagDoing = Integer.parseInt(id.getDeclaredFields()[0].get(obj).toString());
				tagText = Integer.parseInt(id.getDeclaredFields()[1].get(obj).toString());
				tagTime = Integer.parseInt(id.getDeclaredFields()[2].get(obj).toString());
			}
			catch (Exception e)
			{
			}
		}
		tv.setTag(tagText, tv.getText().toString());
		long regTime = toLong(getLongValue(tv.getContext(), key, 0));
		long currentTime = System.currentTimeMillis();
		long l = currentTime - regTime;
		if (validate_second <= 0)
		{
			validate_second = VALIDATE_SEC;
		}
		if (l < validate_second * 1000 && tv.getTag(tagDoing) == null)
		{
			doEnable(l, tv, validate_second);
			return true;
		}
		return false;
	}
	
	private class MyHandler
	        extends
	        TextHttpResponseHandler
	{
		
		@Override
		public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
			if (statusCode > 1000)
			{
				btnVerify.setEnabled(true);
				try
				{
					Util.showToast(bActivity, statusCode == ResultCode.E_1100 ? "该号码未注册" : JSONUtil.getString(responseString));
				}
				catch (JSONException e)
				{
					e.printStackTrace();
				}
			}
		}
		
		@Override
		public void onSuccess(int statusCode, Header[] headers, String responseString) {
			Util.ToastShow(context, "验证码已发送到您的手机上");
			putLongValue(context, RETRIEVE_TIME, System.currentTimeMillis());
			validateRegTime(btnVerify, RETRIEVE_TIME);
		}
		
	}
	
	private class getVerificationHandler
	        extends
	        TextHttpResponseHandler
	{
		
		@Override
		public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
			System.err.println("code1" + responseString);
			if (statusCode > 1000)
			{
				btnVerify.setEnabled(true);
				try
				{
					if (statusCode == 1008)
					{
						Util.showToast(bActivity, JSONUtil.getString(responseString));
					}
					else if (statusCode == 9103)
					{
						Util.showToast(bActivity, JSONUtil.getString(responseString));
					}
					else if (statusCode == 1106)
					{
						//						Util.showToast(bActivity, statusCode == ResultCode.E_1106 ? "账号已存在" : JSONUtil.getString(responseString));
						Util.showToast(bActivity, JSONUtil.getString(responseString));
					}
				}
				catch (JSONException e)
				{
					e.printStackTrace();
				}
			}
		}
		
		@Override
		public void onSuccess(int statusCode, Header[] headers, String responseString) {
			System.err.println("code" + responseString);
			Util.ToastShow(context, "验证码已发送到您的手机上");
			putLongValue(context, RETRIEVE_TIME, System.currentTimeMillis());
			validateRegTime(btnVerify, RETRIEVE_TIME);
		}
		
	}
	
	private class MyAction
	        implements
	        ActionListener
	{
		
		@Override
		public void OK(final Object obj) {
			bActivity.getUIHandler().post(new Runnable()
			{
				
				@Override
				public void run() {
					
					// CheckCodePage page = new CheckCodePage(bActivity);
					// page.setAccountString((String)obj);
					// bActivity.changePage(page, KEEP_LAST_STATUS);
					Util.ToastShow(context, "验证码已发送到您的手机上");
					putLongValue(context, RETRIEVE_TIME, System.currentTimeMillis());
					validateRegTime(btnVerify, RETRIEVE_TIME);
				}
			});
			
		}
		
		@Override
		public void ERROR(final int resultCode, final String message) {
			bActivity.getUIHandler().post(new Runnable()
			{
				@Override
				public void run() {
					btnVerify.setEnabled(true);
					Util.showToast(bActivity, resultCode == ResultCode.E_1100 ? "该号码未注册" : message);
				}
			});
			
		}
		
		@Override
		public void HTTPERROR(int statusCode) {
			
		}
		
	}
	
	private class NextHandler
	        extends
	        TextHttpResponseHandler
	{
		
		@Override
		public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
			if (statusCode > 1000)
			{
				try
				{
					Util.showToast(bActivity, JSONUtil.getString(responseString));
					//		            Util.showToast(bActivity, "验证码错误");
				}
				catch (JSONException e)
				{
					e.printStackTrace();
				}
			}
			
		}
		
		@Override
		public void onSuccess(int statusCode, Header[] headers, String responseString) {
			CheckCodeSetNewPwdPage checkCodeSetNewPwdPage = new CheckCodeSetNewPwdPage(bActivity);
			checkCodeSetNewPwdPage.setVerifyCodeString(mesString);
			checkCodeSetNewPwdPage.setAccountString(mAccount);
			bActivity.changePage(checkCodeSetNewPwdPage, KEEP_LAST_STATUS);
			
		}
		
	}
	
	private class RegisterNextHandler
	        extends
	        TextHttpResponseHandler
	{
		
		@Override
		public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
			System.err.println("code" + responseString);
			if (statusCode > 1000)
			{
				try
				{
					Util.showToast(bActivity, JSONUtil.getString(responseString));
					//		            Util.showToast(bActivity, "验证码错误");
				}
				catch (JSONException e)
				{
					e.printStackTrace();
				}
			}
		}
		
		@Override
		public void onSuccess(int statusCode, Header[] headers, String responseString) {
			System.err.println("code1" + responseString);
			Intent nextIntent = new Intent(bActivity, RegisterInformationActivity.class);
			nextIntent.putExtra("account", mAccount);
			bActivity.startActivity(nextIntent);
		}
		
	}
	
}
